﻿using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using SCZS.Example.AuthenticationCenter.Utility;
using SCZS.Example.Core.ConsulExtend.ClienExtend;
using SCZS.Example.DTOModel;

namespace SCZS.Example.AuthenticationCenter.Controllers
{
    [Route("auth/[controller]")]
    [ApiController]
    public class AuthController : ControllerBase
    {
        private readonly ILogger<AuthController> _logger;
        private readonly ICustomJWTService _iJWTService = null;
        private readonly HttpHelperService _HttpHelperService = null;
        private readonly IConfiguration _IConfiguration = null;
        private readonly AbstractConsulDispatcher _IConsulDispatcher = null;
        public AuthController(ILogger<AuthController> logger, ICustomJWTService service, HttpHelperService httpHelperService, IConfiguration configuration, AbstractConsulDispatcher consulDispatcher)
        {
            this._logger = logger;
            this._iJWTService = service;
            this._HttpHelperService = httpHelperService;
            this._IConfiguration = configuration;
            this._IConsulDispatcher = consulDispatcher;
        }

        [Route("auth/accredit")]
        [HttpPost]
        public async Task<Output<AuthOutput>> Accredit([FromForm] string userAccount, [FromForm] string password)
        {
            Output<AuthOutput> output = new Output<AuthOutput>();
            output.Data = new AuthOutput();
            string requestUrl = $"{this._IConfiguration["VerifyUserUrl"]}?useraccount={userAccount}&password={password}";
            string realUrl =await this._IConsulDispatcher.GetAddress(requestUrl);

            Console.WriteLine($"{requestUrl}--{realUrl}");
            var result = await _HttpHelperService.VerifyUser(realUrl);
            if (result != null && result.IsSuccess)
            {
                string token = this._iJWTService.GetToken(result.Data);
                output.Data.Token = token;
            }
            Console.WriteLine($"Accredit Result : {JsonConvert.SerializeObject(output)}");
            return output;
        }
    }
}
